package edu.mercer.sse.tests.web;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.common.base.Function;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkArgument;

/**
 * Parse Integer size from URL download output.<p>
 * 
 * Examples of input:
 * <ol>
 * <li>http://medapps.mercer.edu downloaded. Size: 108569
 * <li>http://gain.mercer.edu downloaded. Size: 16308
 * </ol>
 * 
 * Examples of output:
 * <ol>
 * <li>108569
 * <li>16308
 * </ol>
 * 
 * @param resultsStr - String line of output as above
 * 
 * @return  Integer - numeric Size of content downloaded
 * 
 * @see Function
 */

public class ParseSizeFunction implements Function<String,Integer>
{
	private final static String URL_DOWNLOAD_REGEX = 
			"[a-zA-Z\\.\\s\\-0-9\\:\\/]{1,200}\\sSize:\\s(?<Size>[0-9]{1,})";
	

	@Override
	public Integer apply( final String resultsStr )
	{
		checkNotNull( resultsStr, "website download: failed parse Size from "
				+ "results, null" );

		checkArgument( resultsStr.length() > 0, "website download: failed "
				+ "parse Size from results, empty length" );
		
		final Pattern sizePattern = Pattern.compile(URL_DOWNLOAD_REGEX);
		
		final Matcher sizeMatcher = sizePattern.matcher( resultsStr );
		
		checkArgument( sizeMatcher.matches(), "size regex pattern not "
				+ "found: " + resultsStr 
				+ ", using pattern: " 
				+ sizePattern.pattern() );
		
		final String sizeFoundStr = sizeMatcher.group( "Size" );
		
		checkNotNull( sizeFoundStr, "website download: failed parse Size "
				+ "from results, null" );

		checkArgument( sizeFoundStr.length() > 0, "website download: "
				+ "failed parse Size from results, empty length" );

		return new Integer( sizeFoundStr );		
		
	}//method


}//class
